package org.example.sensor.service;

import lombok.extern.slf4j.Slf4j;

import org.example.sensor.dox.User;
import org.example.sensor.exception.XException;
import org.example.sensor.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;
    public User getUserByaccount(String account) {
        return userRepository.findByAccount(account);
    }
    //重置密码
    @CachePut(value = "user",key = "#account")
    @Transactional
    public void updateUserPassword(String account) {
        User user = getUserByaccount(account);
        if (user == null) {
          throw   XException.builder().number(400).message("用户不存在").build();
        }
        user.setPassword(passwordEncoder.encode(account));
        userRepository.save(user);
    }
    @CachePut(value = "user",key = "#account")
    @Transactional
    public void updateUserPassword(String account,String password) {
        User user = queryUser(account);
        if (user == null) {
            throw   XException.builder().number(400).message("用户不存在").build();
        }
        user.setPassword(passwordEncoder.encode(password));
        userRepository.save(user);
    }
    @Transactional
    public void addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getAccount()));
        user.setRole(User.USER);
        userRepository.save(user);
    }
    @Transactional
    public void addUserByRe(User user) {
        user.setName("role");
        user.setRole(User.USER);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
    }
    public List<User> listUsers() {
        return userRepository.findAllById();
    }
    @CacheEvict(value = "user",key = "#account")
    public void deleteUser(String account) {
        User user = userRepository.findByAccount(account);
        if (user == null || user.getRole().equals(User.ADMIN)) {
            throw   XException.builder().number(400).message("用户不存在或者用户为管理员").build();
        }
        userRepository.delete(user);
    }
    @Cacheable(value = "user",key = "#account")
    public User queryUser(String account) {
        User byAccount = userRepository.findByAccount(account);
        if (byAccount == null) {
            throw   XException.builder().number(400).message("用户不存在").build();
        }
        return byAccount;
    }
}
